package com.lifuixng.picturebackend.manage.upload;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.lifuixng.picturebackend.config.CosClientConfig;
import com.lifuixng.picturebackend.exception.BusinessException;
import com.lifuixng.picturebackend.exception.ErrorCode;
import com.lifuixng.picturebackend.manage.CosManager;
import com.lifuixng.picturebackend.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @Author Mr.LiFuXing
 * @Date 2024/12/22 20:32
 * @Title PictureUploadTemplate
 * @Package com.lifuixng.picturebackend.manage.upload
 */

@Slf4j
public abstract class PictureUploadTemplate {


    @Resource
    private CosManager cosManager;

    @Resource
    private CosClientConfig cosClientConfig;

    public final UploadPictureResult uploadPicture(Object inputSource, String uploadPicturePrefix) {
        // 图片校验
        verifyPicture(inputSource);
        // 2. 以防图片名称重复覆盖图片，自己生成一个唯一的图片名
        // day+uuid+.jpg
        String uuid = RandomUtil.randomString(8);
        // String originalFilename = multipartFile.getOriginalFilename();
        String originalFilename = getOriginalFilename(inputSource);
        // 生成图片的全名称 2024-12-18-12345678.jpg
        String uploadFilename = String.format("%s-%s.%s",
                DateUtil.formatDate(new Date()),
                uuid,
                FileUtil.getSuffix(originalFilename));

        // 上传的位置（路径） 前缀＋图名全名 /test/2024-12-18-12345678.jpg
        String uploadPath = String.format("/%s/%s", uploadPicturePrefix, uploadFilename);
        // 3. 图片上传
        File file = null;
        try {
            file = File.createTempFile(uploadPath, null);
            // inputSource.transferTo(file);
            processFile(inputSource, file);
            // 图片上传返回图片对象
            PutObjectResult objectResult = cosManager.putPictureObject(uploadPath, file);
            // 获取到图片信息对象 （数据万象处理）
            ImageInfo imageInfo = objectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            ProcessResults processResults = objectResult.getCiUploadResult().getProcessResults();
            // 返回数据万象处理的图片  webp、缩略图
            List<CIObject> processResultsObjectList = processResults.getObjectList();
            if (processResultsObjectList != null) {
                // 获取压缩图片 webp
                CIObject compressCiObject = processResultsObjectList.get(0);
                // 由于小于20kb的图片没有缩略图，则将缩略图默认为webp
                CIObject thumbnailCiObject = compressCiObject;
                // 说明有缩略图
                if (processResultsObjectList.size() > 1) {
                    thumbnailCiObject = processResultsObjectList.get(1);
                }                // 获取图片缩略图

                return buildUploadPictureResult(originalFilename, compressCiObject, thumbnailCiObject);
            }
            return buildUploadPictureResult(originalFilename, file, uploadPath, imageInfo);
        } catch (Exception e) {
            log.error("图片上传到COS失败！", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "图片上传失败");
        } finally {

            if (file != null) {
                boolean delete = file.delete();
                if (!delete) {
                    log.error("文件销毁失败{}", file.getAbsoluteFile());
                }
            }
        }
    }

    private UploadPictureResult buildUploadPictureResult(String originalFilename, CIObject compressCiObject, CIObject thumbnailCiObject) {

        int picWidth = compressCiObject.getWidth();
        int picHeight = compressCiObject.getHeight();
        // 计算宽高比
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        // 封装UploadPictureResult对象(图片的详细信息)
        return UploadPictureResult.builder()
                .picFormat(compressCiObject.getFormat())
                .picName(FileUtil.mainName(originalFilename))
                .picWidth(picWidth)
                .picHeight(picHeight)
                .picScale(picScale)
                .picSize(compressCiObject.getSize().longValue())
                // https://li-yoy-picture-1333315463.cos.ap-beijing.myqcloud.com/图片路径
                .url(cosClientConfig.getHost() + "/" + compressCiObject.getKey())
                .thumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey())
                .build();
    }

    /**
     * 校验文件 图片或URL
     *
     * @param inputSource
     */
    protected abstract void verifyPicture(Object inputSource);

    /**
     * 获取文件名
     *
     * @param inputSource
     * @return
     */
    protected abstract String getOriginalFilename(Object inputSource);

    /**
     * 将文件转为本地文件
     *
     * @param inputSource
     * @param file
     */
    protected abstract void processFile(Object inputSource, File file) throws IOException;


    public UploadPictureResult buildUploadPictureResult(String originalFilename, File file, String uploadPath, ImageInfo imageInfo) {
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        // 计算宽高比
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        // 封装UploadPictureResult对象(图片的详细信息)
        return UploadPictureResult.builder()
                .picFormat(imageInfo.getFormat())
                .picName(FileUtil.mainName(originalFilename))
                .picWidth(picWidth)
                .picHeight(picHeight)
                .picScale(picScale)
                .picSize(FileUtil.size(file))
                // https://li-yoy-picture-1333315463.cos.ap-beijing.myqcloud.com/图片路径
                .url(cosClientConfig.getHost() + "/" + uploadPath)
                .build();
    }


}
